package dao

import (
	"errors"
	"fmt"
	"gorm.io/gorm"
	"hcy-api/structs/sys"
	"hcy-api/structs/tables"
	"sys/global"
)

var UserDB = new(userRepository)

type userRepository struct{}

func (r userRepository) FindList() (li []tables.User, err error) {
	err = global.DB.Model(&tables.User{}).Where("user_id >0").Preload("Extend").Find(&li).Error
	return
}
func (r userRepository) FindListByOrgIds(orgIds []int64) (li []tables.User, err error) {
	err = global.DB.Model(&tables.User{}).Where("org_id in ?", orgIds).Preload("Extend").Find(&li).Error
	return
}

func (r userRepository) FindPage(in sys.SearchUser, uid int64) (li []tables.User, total int64, err error) {
	tx := global.DB.Model(&tables.User{}).Where("username like ? ", fmt.Sprintf("%%%s%%", in.Username))
	if in.OrgId != 0 {
		tx.Where("org_id = ? ", in.OrgId)
	} else {
		tx.Where("org_id in (select org_id from sys_map_user_org where user_id =?) ", uid)
	}
	tx.Preload("Extend")
	err = tx.Count(&total).Limit(in.PageSize).Offset((in.PageNum - 1) * in.PageSize).Find(&li).Error
	return
}

// UsernameExist 检查账户是否已经存在，true 存在
func (r userRepository) UsernameExist(username string) (*tables.User, bool) {
	var u = new(tables.User)
	err := global.DB.Model(&tables.User{}).Where(&tables.User{Username: username}).Find(&u).Error
	if err != nil {
		return nil, true
	}
	return u, u.UserId > 0
}

func (r userRepository) FindById(userId int64) (*tables.User, error) {
	user := new(tables.User)
	var err error
	if err = global.DB.First(user, userId).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fmt.Errorf("sys not exist")
	}
	err = global.DB.Model(user).Association("Extend").Find(&user.Extend)
	return user, err
}

func (r userRepository) FindUserByAccount(username string) (user *tables.User, err error) {
	if err = global.DB.Where("username = ?", username).Find(&user).Error; errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, fmt.Errorf("sys not exist")
	}
	err = global.DB.Model(user).Association("Extend").Find(&user.Extend)
	return
}

func (r userRepository) DeleteById(id int64) (err error) {
	return global.DB.Delete(&tables.User{}, id).Error
}

func (r userRepository) DeleteByIds(ids []int64) (err error) {
	if len(ids) > 0 {
		return global.DB.Where("user_id in ?", ids).Delete(&tables.User{}).Error
	}
	return nil
}

func (r userRepository) UpdateById(u *tables.User) (err error) {
	tx := global.DB.Begin()
	err = global.DB.Save(&u).Error
	err = global.DB.Save(&u.Extend).Error
	tx.Commit()
	return err
}

func (r userRepository) FindUserRoleList(userId int64) (li []tables.Role, err error) {
	err = global.DB.Raw("select * from sys_role where role_id in (select role_id from  sys_map_user_role where user_id = ? )", userId).Scan(&li).Error
	return
}

func (r userRepository) DeleteMapUserForRole(userId int64) (err error) {
	err = global.DB.Exec("delete from sys_map_user_role where user_id = ? ", userId).Error
	return
}

func (r userRepository) FindOrgIds(userId int64) (orgIds []int64, err error) {
	orgIds = make([]int64, 0)
	err = global.DB.Raw("select org_id from sys_map_user_org where user_id = ?", userId).Scan(&orgIds).Error
	return
}

func (r userRepository) FindRoleIds(userId int64) (roleIds []int64, err error) {
	roleIds = make([]int64, 0)
	err = global.DB.Raw("select role_id from  sys_map_user_role where user_id = ?", userId).Scan(&roleIds).Error
	return
}

// FindOrgListByUserId 查询用户关联的部门列表，也就是用户能管理的部门范围
func (r userRepository) FindOrgListByUserId(userId int64) (li []tables.Org, err error) {
	err = global.DB.Model(&tables.Org{}).Where("id in (select  org_id from sys_map_user_org where user_id =?)", userId).Find(&li).Error
	return
}
